# -*- coding: utf-8 -*-

from abc import ABC
from app.models import db_session
from app.views import CommonHandler
from app.models.model import MetaModel
from app.models.cod import Sign, MapAssembly, name_by_key


class MetasHandler(CommonHandler, ABC):
    async def get(self):
        tree, mine_code = {}, self.get_argument("mine_code", None)

        pieces = db_session().query(MetaModel).filter(MetaModel.mine_code == mine_code)\
            .group_by(MetaModel.sign).group_by(MetaModel.piece)\
            .order_by(MetaModel.sign).all()
        for p in pieces:
            sign = name_by_key(Sign, p.sign)
            piece = name_by_key(MapAssembly, p.piece)
            if sign in tree.keys():
                tree[sign][piece] = []
            else:
                tree[sign] = {}
                tree[sign][piece] = []

        metas = db_session().query(MetaModel).filter(MetaModel.mine_code == mine_code).all()
        for meta in metas:
            sign = name_by_key(Sign, meta.sign)
            piece = name_by_key(MapAssembly, meta.piece)
            tree[sign][piece].append({'name': meta.name, 'meta_id': meta.meta_id})

        await self.response(data=tree)

    async def post(self):
        params, cont = self.json_params(), {}
        no, size = params['no'], params['size']

        query = db_session().query(MetaModel).filter()
        query = query.order_by(MetaModel.create_time.desc())

        cont['total'] = query.count()
        metas = query.limit(size).offset((no - 1) * size)
        cont['data'] = [meta.dxf() for meta in metas]

        await self.response(data=cont)

    async def put(self):
        pass

    async def delete(self):
        pass
